import axios from "axios";
import { message } from "antd";
const baseUrl = import.meta.env.VITE_BASE_URL;
const instance = axios.create({
  baseURL: baseUrl,
  timeout: 3000,
  timeoutErrorMessage: "请求超时，请刷新重试",
  withCredentials: true,
});

instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    config.headers["Content-Type"] = "application/json";
    config.headers["X-Requested-With"] = "XMLHttpRequest";

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data.code === 40001) {
      window.location.href = "/login";
    } else if (data.code != 200) {
      message.error(data.msg);
    }
    return data.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default {
  get<T>(url: string, params?: object): Promise<T> {
    return instance.get(url, { params });
  },
  post<T>(url: string, data?: object): Promise<T> {
    return instance.post(url, data);
  },
};
